import useToast from '@/hooks/useToast';

export interface IValidator<T> {
  key: keyof T;
  requiredMsg?: string;
  name: string;
  required?: boolean;
  rule?: RegExp | ((value: T[keyof T]) => boolean); // 验证规则
}

/**
 * 验证对象是否符合规则
 * @param validateObj - 要验证的对象
 * @param validators - 验证规则数组
 * @returns boolean - 返回验证结果
 */
const { showToast } = useToast();
export default function validate<T extends Record<string, any>>(obj: Partial<T>, validators: IValidator<T>[]): boolean {
  for (const validator of validators) {
    const { key, name, requiredMsg, required = false, rule } = validator;

    const value = obj[key];

    if (required && (value === undefined || value === null || value === '')) {
      showToast(requiredMsg || `必填字段 ${name} 为空`);
      return false;
    }

    // 如果字段存在且有验证规则，进行规则验证
    if (value !== undefined && rule) {
      if (rule instanceof RegExp) {
        if (!rule.test(String(value))) {
          showToast(`请输入正确格式的${name}`);
          return false;
        }
      } else if (typeof rule === 'function') {
        if (!rule(value)) {
          showToast(`请输入正确格式的${name}`);
          return false;
        }
      }
    }
  }

  return true;
}

/**
 * 手机号验证
 * @param value
 */
export function validatePhone(value: string): boolean {
  return /^1[3-9]\d{9}$/.test(value);
}
